import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.读取请求参数
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //2.验证
        if (!"zhangsan".equals(username) || !"123".equals(password)) {
            //登陆失败
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前的用户名或密码错误!");
            return;
        }
        //3.登陆成功创建会话
        //为 true 是没有找到 sessionId 可以自动创建 session 对象
        HttpSession session = req.getSession(true);
        session.setAttribute("username", username);
        session.setAttribute("password", password);
        session.setAttribute("LoginTime", System.currentTimeMillis());
        //4.登录成功,跳转网站首页
        resp.sendRedirect("index");
    }
}
